package com.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Mono;

import java.util.Map;

@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }


//    @Bean
    public RouteLocator myRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(p -> p.path("/test/*").uri("http://localhost:9005"))
//                .route(p -> p.path("/service").filters(f ->f.prefixPath("/test")).uri("http://localhost:9005"))
                .route(p -> p.path("/fallback").filters(f -> f.hystrix(h->{h.setFallbackUri("forward:/fallback/error");})).uri("http://localhost:9000"))
                .build();
    }


    /**
     *  限流器获取用户
     * @return
     */
    @Bean
    KeyResolver userKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }


    /**
     *  自定义限流器   在配置文件中使用SpEL表达式引用  #{@myRateLimiter}
     * @return
     */
//    @Bean
    RateLimiter myRateLimiter(){
        return new RateLimiter() {
            @Override
            public Mono<Response> isAllowed(String routeId, String id) {
                return null;
            }

            @Override
            public Map getConfig() {
                return null;
            }

            @Override
            public Class getConfigClass() {
                return null;
            }

            @Override
            public Object newConfig() {
                return null;
            }
        };
    }

}
